/**
 * Metadata React Query Hooks
 * 元数据搜索与查询钩子 (FR-010 ~ FR-012)
 */

import { useQuery, useQueryClient, UseQueryResult } from '@tanstack/react-query'
import * as metadataApi from '@/services/api/metadata'
import type { PageResponse, MetadataTable, MetadataColumn } from '@/services/models/types'

// Query Keys for metadata operations
export const metadataQueryKeys = {
  all: ['metadata'] as const,
  tables: {
    all: () => [...metadataQueryKeys.all, 'tables'] as const,
    lists: () => [...metadataQueryKeys.tables.all(), 'list'] as const,
    list: (filters: Record<string, any>) => [...metadataQueryKeys.tables.lists(), filters] as const,
    details: () => [...metadataQueryKeys.tables.all(), 'detail'] as const,
    detail: (id: number) => [...metadataQueryKeys.tables.details(), id] as const,
  },
  columns: {
    all: () => [...metadataQueryKeys.all, 'columns'] as const,
    byTable: (tableId: number) => [...metadataQueryKeys.columns.all(), tableId] as const,
  },
}

// ============================================
// Query Hooks - 查询钩子
// ============================================

/**
 * 元数据表搜索 (FR-010)
 * 支持按表名、注释、数据源、数据库类型等条件搜索
 */
export const useSearchTables = (params: any, options?: any): UseQueryResult<PageResponse<MetadataTable>> => {
  return useQuery<PageResponse<MetadataTable>>({
    queryKey: metadataQueryKeys.tables.list(params),
    queryFn: async () => {
      const response = await metadataApi.searchTables(params)
      if (!response.success) throw new Error(response.message)
      return response.data!
    },
    staleTime: 2 * 60 * 1000, // 2 minutes - metadata changes infrequently
    gcTime: 5 * 60 * 1000, // 5 minutes
    ...options,
  })
}

/**
 * 元数据表详情查询 (FR-011)
 * 查询单张表的完整元数据信息
 */
export const useTableDetail = (id: number, options?: any): UseQueryResult<MetadataTable> => {
  return useQuery<MetadataTable>({
    queryKey: metadataQueryKeys.tables.detail(id),
    queryFn: async () => {
      const response = await metadataApi.getTableDetail(id)
      if (!response.success) throw new Error(response.message)
      return response.data!
    },
    enabled: !!id,
    staleTime: 5 * 60 * 1000, // 5 minutes
    ...options,
  })
}

/**
 * 表字段列表查询 (FR-012)
 * 查询表的所有字段元数据(字段名、类型、长度、注释等)
 */
export const useTableColumns = (tableId: number, options?: any): UseQueryResult<MetadataColumn[]> => {
  return useQuery<MetadataColumn[]>({
    queryKey: metadataQueryKeys.columns.byTable(tableId),
    queryFn: async () => {
      const response = await metadataApi.getTableColumns(tableId)
      if (!response.success) throw new Error(response.message)

      // 后端返回Page<MetadataColumn>,提取content数组
      const data = response.data as any
      if (data && data.content && Array.isArray(data.content)) {
        return data.content
      }

      // 如果已经是数组,直接返回
      if (Array.isArray(data)) {
        return data
      }

      return []
    },
    enabled: !!tableId,
    staleTime: 5 * 60 * 1000, // 5 minutes
    ...options,
  })
}

// ============================================
// Composite Hooks - 组合钩子
// ============================================

/**
 * 表详情与字段组合查询
 * 同时加载表详情和字段信息,适用于元数据详情页
 */
export const useTableWithColumns = (tableId: number, options?: any) => {
  const tableQuery = useTableDetail(tableId, options)
  const columnsQuery = useTableColumns(tableId, {
    ...options,
    enabled: tableQuery.isSuccess && !!tableId,
  })

  return {
    table: tableQuery.data,
    columns: columnsQuery.data || [],
    isLoading: tableQuery.isLoading || columnsQuery.isLoading,
    isError: tableQuery.isError || columnsQuery.isError,
    error: tableQuery.error || columnsQuery.error,
    refetch: () => {
      tableQuery.refetch()
      columnsQuery.refetch()
    },
  }
}

/**
 * 预加载表详情
 * 用于表搜索列表,鼠标hover时预加载详情,提升用户体验
 */
export const usePrefetchTableDetail = () => {
  const queryClient = useQueryClient()

  return (tableId: number) => {
    queryClient.prefetchQuery({
      queryKey: metadataQueryKeys.tables.detail(tableId),
      queryFn: async () => {
        const response = await metadataApi.getTableDetail(tableId)
        if (!response.success) throw new Error(response.message)
        return response.data!
      },
      staleTime: 5 * 60 * 1000,
    })
  }
}

/**
 * 预加载字段列表
 * 用于表详情展开时预加载字段信息
 */
export const usePrefetchTableColumns = () => {
  const queryClient = useQueryClient()

  return (tableId: number) => {
    queryClient.prefetchQuery({
      queryKey: metadataQueryKeys.columns.byTable(tableId),
      queryFn: async () => {
        const response = await metadataApi.getTableColumns(tableId)
        if (!response.success) throw new Error(response.message)

        // 后端返回Page<MetadataColumn>,提取content数组
        const data = response.data as any
        if (data && data.content && Array.isArray(data.content)) {
          return data.content
        }

        if (Array.isArray(data)) {
          return data
        }

        return []
      },
      staleTime: 5 * 60 * 1000,
    })
  }
}
